package com.rongke.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.rongke.mapper.OrderGoodsMapper;
import com.rongke.mapper.ShoppingCarMapper;
import com.rongke.model.Muser;
import com.rongke.model.OrderGoods;
import com.rongke.model.Orders;
import com.rongke.model.ShoppingCar;
import com.rongke.redis.CacheUtil;
import com.rongke.service.MuserService;
import com.rongke.service.OrdersService;
import com.rongke.service.ShoppingCarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @ShoppingCarServiceImpl
 * @购物车ServiceImpl
 * @version : Ver 1.0
 */
@Service
public class ShoppingCarServiceImpl extends ServiceImpl<ShoppingCarMapper, ShoppingCar> implements ShoppingCarService {

    @Autowired
    private ShoppingCarMapper shoppingCarMapper;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private MuserService muserService;

    @Autowired
    private OrderGoodsMapper orderGoodsMapper;

    /**
     * @根据条件查找购物车
     * @param shoppingCar
     * @return
     */
    @Override
    public List<ShoppingCar> selectByCondition(ShoppingCar shoppingCar) {
        return shoppingCarMapper.selectByCondition(shoppingCar);
    }

    @Override
    public void emptyShoppingCart(Long orderId) {
        Orders orders=ordersService.selectById(orderId);
        Muser muser=muserService.selectById(orders.getMuserId());
        EntityWrapper<OrderGoods> ew=new EntityWrapper<>();
        ew.eq("order_id",orders.getId());
        List<OrderGoods> orderGoodses=orderGoodsMapper.selectList(ew);
       Set set = cacheUtil.getSet("shopCar" + muser.getId());
        Object obj[] = set.toArray();
        String str2[] = null;
        List<JSONObject> jsonObjects=new ArrayList<>();
            for(int m=0;m<obj.length;m++){
                JSONObject jsonCar = JSONObject.parseObject(String.valueOf(obj[m]));
                int i=0,y=orderGoodses.size();
                for(;i<y;i++){
                    OrderGoods orderGoods=orderGoodses.get(i);
                if (jsonCar.getString("skuId").equals(String.valueOf(orderGoods.getSkuId()))) {
                    break;
                }
            }
             if(i==y){
                 jsonObjects.add(jsonCar);
             }
        }
        cacheUtil.delkey("shopCar"+muser.getId());
      if(!jsonObjects.isEmpty()){
          str2=new String[jsonObjects.size()];
          for (int i=0,y=jsonObjects.size();i<y;i++){
              JSONObject json=jsonObjects.get(i);
              str2[i]=json.toJSONString();
          }
          cacheUtil.addSet("shopCar"+muser.getId(),str2);
      }

    }
}
